const FtpSvr = require('ftp-srv');
const ftp = require("basic-ftp");// ftp客户端
const fs = require('fs')
const path = require('path');
const address = require('address');
const HOST = process.env.FTP_HOST || address.ip() || "127.0.0.1";
const PORT = process.env.FTP_PORT || "21";
const ftpServer = new FtpSvr(`ftp://${HOST}:${PORT}`, {});
/**
 *  niahofdfn
 */
ftpServer.on('login', (data, resolve, reject) => {
    if (data.username === 'hansight' && data.password === 'hansight.com') {
        resolve({
            root: path.join(process.cwd(), 'upload'),
            cwd: '/'
        });
        // console.log(data.connection)
        data.connection.on('RETR', (error, filePath) => {
            if (error) {
                console.log(error)
                return
            }
            console.log(filePath)
        });
        data.connection.on('STOR', async (error, fileName) => {
            if (error) {
                console.log(error)
                return
            }

            if(fileName.startsWith("/nanjing")){//只有当是成都ui上传到成都, 才会发起同步, 如果是对方服务器上传文件, 则不需要putFile
                // console.log(fileName)
                putFile(fileName)
                //将每次上传的文件日志存在store.json文件中
                let stroe = await getStore('./store.json')//应该使用try包裹以下
                stroe = JSON.parse(stroe)
                stroe.push({time: new Date().toDateString(),filename: fileName,"directive": "STOR"})
                await writeStore('./store.json', JSON.stringify(stroe))//因为使用try包裹以下
            }
        });
    } else {
        reject('no');
    }
});


ftpServer.listen().then(() => {
    console.log('ftp server listening at', HOST + ':' + PORT);
});


/**
 * 再stor事件触发的时候, 将文件上传到对方服务器
 * 存在的可能问题?
 *  1. 如果文件过大, 未完成上传到对方服务器, 而此时出现己方, 重新上传文件到自己服务器. 会造成对方文件残缺 --- 不存在.
 *
 *
 */
async function putFile(fileName) {

    const client = new ftp.Client()//使用ftp模块, new了一个客户端
    try {//尝试连接
        await client.access({
            host: "172.16.150.182",
            port: 8082,
            user: "hansight",
            password: "hansight.com",
        })
        // console.log((await client.list()).map( item => item.name))
        await client.ensureDir(fileName.replace(/[\w-]+\.[\w]+$/, ""))//确保对方服务器上已经存在目录结构
        //将刚刚完成上传的文件上传到对方服务器
        let msg = await client.upload(fs.createReadStream(process.cwd() + "/upload/" + fileName), fileName.match(/[\w-]+\.[\w]+$/)[0])
    }
    catch (err) {
        console.log(err)
    }
    client.close()
}


/**
 * 读取store.json文件
 * @param {string} url// 相对于盘符的地址
 */
function getStore(url) {
    return new Promise((resolve, reject) => {
        fs.readFile(url, (err, data) => {
            if (err) reject(err);
            resolve(data)
        })
    })
}

/**
 * 将内容写如store.json文件
 *
 * @param {*} url
 * @param {*} data
 * @returns
 */
function writeStore(url, data) {
    return new Promise((resolve, reject) => {
        fs.writeFile(url, data, err => {
            if (err) reject(err)
        })
    })
}


